package org.crackjack.android.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.crackjack.android.model.Appointment;
import org.crackjack.android.model.Category;
import org.crackjack.android.model.Profile;

public class ResponseJsonParser {

    public static String parseAuthorizationJson(String json) throws JsonParseException, JsonMappingException,
            IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getJsonFactory();
        JsonParser parser = factory.createJsonParser(json);
        JsonNode node = mapper.readTree(parser);

        return node.get("status").asText();

    }

    public static List<Appointment> parseAppointmentsJson(String json) throws JsonParseException, JsonMappingException,
            IOException {

        List<Appointment> appointments = new ArrayList<Appointment>();

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getJsonFactory();
        JsonParser parser = factory.createJsonParser(json);
        JsonNode node = mapper.readTree(parser);
        Iterator<JsonNode> iterator = node.iterator();

        while (iterator.hasNext()) {

            Appointment appointment = new Appointment();

            JsonNode jsonAappointment = iterator.next();
            appointment.setId(jsonAappointment.get("id").asLong());
            appointment.setName(jsonAappointment.get("name").asText());
            appointment.setDescription(jsonAappointment.get("description").asText());
            appointment.setRating(jsonAappointment.get("rating").asDouble());

            Category category = new Category();

            JsonNode jsonCategory = jsonAappointment.get("category");
            category.setId(jsonCategory.get("id").asLong());
            category.setName(jsonCategory.get("name").asText());

            appointment.setCategory(category);

            Profile profile = new Profile();
            JsonNode jsonAppointmentOwner = jsonAappointment.get("appointmentOwner");
            profile.setId(jsonAppointmentOwner.get("id").asLong());
            profile.setLogin(jsonAppointmentOwner.get("login").asText());

            appointment.setAppointmentOwner(profile);

            appointments.add(appointment);

        }

        return appointments;

    }

}
